//
//  FyUtils.m
//  fydata_demo
//
//  Created by 曹燃 on 15-1-23.
//  Copyright (c) 2015年 feiyu.com. All rights reserved.
//

#import "CommonCrypto/CommonDigest.h"
#import "FYUtils.h"

@implementation FYUtils

// JSON-->NSDictionary
+ (NSDictionary*)fyJsonToDictionary:(NSString *)inputText {
    
    NSData *data= [inputText dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                    options:NSJSONReadingAllowFragments error:&error];
    
    if (error == nil && [jsonObject isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dictionary = (NSDictionary *)jsonObject;
        return dictionary;
    }
    
    return nil;
}

//Dictionary-->JSON
+ (NSString*)fyDictionaryToJson:(NSDictionary *)dic {
    
    NSData *jsonData = nil;
    if (dic != nil) {
        
        jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                   options:kNilOptions
                                                     error:nil];
    }
    
    if (jsonData == nil ) {
        return @"";
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}

//Json--> Array
+ (NSArray*)arrayWithJsonString:(NSString*)jsonString {
    NSData *data= [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                    options:NSJSONReadingAllowFragments error:&error];
    
    if (error == nil && [jsonObject isKindOfClass:[NSArray class]]) {
        NSArray *array = (NSArray *)jsonObject;
        return array;
    }
    
    return nil;
}

//MD5 字符串加密
+ (NSString*) fyMd5Encrypt:(NSString *)inputText {
    
    const char *cStr = [inputText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}

// 1.dictionary按key排序 2.组合URL参数字符串 3.URL编码 4.生成签名
+ (NSString*) fyGenerateSign:(NSDictionary *)dict secret:(NSString *)secret {
    
    NSMutableString *mtStr = [NSMutableString stringWithCapacity:3];
    NSArray *arr =  [[dict allKeys] sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
    
    for (NSString *key in arr) {
        [mtStr appendString:key];
        [mtStr appendString:@"="];
        [mtStr appendString:dict[key]];
        if ([arr indexOfObject:key] < (arr.count - 1)) {
            [mtStr appendString:@"&"];
        }
    }
    
    NSString *str = [NSString stringWithFormat:@"%@&%@", [FYUtils fyUrlEncode:mtStr], secret];
    return [FYUtils fyMd5Encrypt:str];
}

// URL编码
+ (NSString*) fyUrlEncode:(NSString*)string {
    CFStringRef escaped =
    CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            (CFStringRef)string,
                                            NULL,
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                            kCFStringEncodingUTF8);
    return (__bridge NSString *)(escaped);
}

//URL解码
+ (NSString*)fyUrlDecode:(NSString*)str {
    
    NSString *result = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}

// URL参数字符串解析成dictionary
+ (NSDictionary*)fyUrlParameterToDictionary:(NSString*)str {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:3];
    
    NSArray *urlComps = [str componentsSeparatedByString:@"&"];
    
    if([urlComps count]) {
        NSArray *parameterComps = nil;
        for (NSString *parameterStr in urlComps) {
            parameterComps = [parameterStr componentsSeparatedByString:@"="];
            NSString *key = [FYUtils fyUrlDecode:[parameterComps objectAtIndex:0]];
            NSString *value = [FYUtils fyUrlDecode:[parameterComps objectAtIndex:1]];
            [parameters setObject:value forKey:key];
        }
        return parameters;
    } else {
        return nil;
    }
}

//dictionary转成URL参数字符串
+ (NSString*) fyDictionaryToParameter:(NSDictionary*)dict {
    
    NSMutableString *mtStr = [NSMutableString stringWithCapacity:3];
    NSArray *arr =  [[dict allKeys] sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
    
    for (NSString *key in arr) {
        [mtStr appendString:key];
        [mtStr appendString:@"="];
        [mtStr appendString:dict[key]];
        if ([arr indexOfObject:key] < (arr.count - 1)) {
            [mtStr appendString:@"&"];
        }
    }
    
    return mtStr;
}

// 获取IDFA
+ (NSString*) fyGetIdfa {
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
    if (NSClassFromString(@"ASIdentifierManager")) {
        if(ASIdentifierManager.sharedManager.isAdvertisingTrackingEnabled) {
            NSString *idfa = ASIdentifierManager.sharedManager.advertisingIdentifier.UUIDString;
            return idfa == nil? @"": idfa;
        }
    }
#endif
    return @"";
}

// 获取IDFV
+ (NSString*) fyGetIdfv {
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
    if([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) {
        NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        return idfv == nil? @"": idfv;
    }
#endif
    return @"";
}

// 生成设备ID
+ (NSString*) fyGenerateDeviceId {
    
    NSString *deviceId = [FYUtils fyGetIdfv];
    
    if (deviceId != nil && deviceId.length > 0) {
        return deviceId;
    }
    
    deviceId = [FYUtils fyGetIdfa];
    
    if (deviceId != nil && deviceId.length > 0) {
        return deviceId;
    }
    
    deviceId = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, CFUUIDCreate(kCFAllocatorDefault)));
    
    return deviceId;
}

//屏幕宽
+ (CGFloat) fyScreenWidth {
    CGFloat w = [[UIScreen mainScreen] bounds].size.width;
    CGFloat h = [[UIScreen mainScreen] bounds].size.height;
    
    if (fyIsLandscape) {
        return MAX(w, h);
    }
    if (fyIsPortrait){
        return MIN(w, h);
    }
    return w;
}

//屏幕长
+ (CGFloat) fyScreenHeight {
    CGFloat w = [[UIScreen mainScreen] bounds].size.width;
    CGFloat h = [[UIScreen mainScreen] bounds].size.height;
    
    if (fyIsLandscape) {
        return MIN(w, h);
    }
    if (fyIsPortrait) {
        return MAX(w, h);
    }
    return w;
}

//是否横屏
//+ (BOOL)fyIsLandscape {
//    if([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight)
//    {
//        return YES;
//    }
//    return NO;
//}

//是否竖屏
//+ (BOOL)fyIsPortrait {
//    if ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)
//    {
//        return YES;
//    }
//    return NO;
//}

//获取时间戳
+ (NSString*)fyGetTimeStamp {
    
    return [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
}

//获取系统时间(yyyyMMddHHmmss)
+ (NSString*)fyGetSystemTime {
    NSDate *currentTime = [NSDate date];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale currentLocale]];
    formatter.timeStyle = NSDateFormatterShortStyle;
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateString = [formatter stringFromDate:currentTime];
    
    return dateString;
}

//数组排序
+ (NSArray*)fySortArray:(NSArray*)array {
    
    NSComparator cmptr = ^(id obj1, id obj2){
        if ([obj1 longLongValue] < [obj2 longLongValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };
    return [array sortedArrayUsingComparator:cmptr];
}

//去除string中的空格
+ (NSString*)fyRemoveWhiteSpace:(NSString*)string {
    return [string stringByReplacingOccurrencesOfString:@"\\s" withString:@""
                                                options:NSRegularExpressionSearch
                                                  range:NSMakeRange(0, [string length])];
}

//测试注册的邮箱或者电话号码是否符合要求
+ (BOOL)fyIsValidateEmailAndTel:(NSString*) inputText {
    NSString *patternTel = @"^1[0-9]{10}$";
    NSString *patternEmail = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSError *err = nil;
    NSRegularExpression *telExp = [NSRegularExpression regularExpressionWithPattern:patternTel options:NSRegularExpressionCaseInsensitive error:&err];
    NSRegularExpression *emailExp =[NSRegularExpression regularExpressionWithPattern:patternEmail options:0 error:&err];
    
    NSTextCheckingResult * isMatchTel = [telExp firstMatchInString:inputText options:0 range:NSMakeRange(0, [inputText length])];
    NSTextCheckingResult *isMatchEmail = [emailExp firstMatchInString:inputText options:0 range:NSMakeRange(0, [inputText length])];
    
    if (isMatchEmail||isMatchTel) {
        return YES;
    }
    return NO;
}

//判断有没有空格
+ (BOOL)fyHasWhiteSpace:(NSString*)string {
    NSRange range = [string rangeOfString:@" "];
    if (range.location != NSNotFound) {
        return YES;
    }else {
        return NO;
    }
}

//限制字符串长度
+ (NSString*)fyLimitStringLength:(NSString*)str length:(NSInteger)length {
    
    NSString *limStr = nil;
    
    if (str.length > length) {
        
        limStr = [str substringWithRange:NSMakeRange(0, length)];
        limStr = [NSString stringWithFormat:@"%@..", limStr];
    } else {
        
        limStr = str;
    }
    return limStr;
}

//根据颜色生成相应的图片
+ (UIImage *)fyImageWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

//根据十六进制色值生成颜色
+ (UIColor*)fyColorWithHexString:(NSString*)hex alpha:(CGFloat)alpha {
    
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    
    if ([cString length] != 6) return  [UIColor grayColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:alpha];
}

//屏幕截图
+ (void)fyScreenShot {
    
    UIViewController *currentVC = [FYUtils fyGetCurrentVC];
    
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){
        UIGraphicsBeginImageContextWithOptions(currentVC.view.bounds.size, NO, [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(currentVC.view.bounds.size);
    }
    
    [currentVC.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)fyGetCurrentVC {
    
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    } else {
        result = window.rootViewController;
    }
    
    return result;
}


@end


